package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.Category;
import com.itheima.pojo.R;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    CategoryService categoryService;

    //分页查询
    @GetMapping("/page")
    public R<IPage> findAll(Integer page, Integer pageSize) {

        IPage<Category> pa = new Page<>(page, pageSize);
        categoryService.page(pa);

        return R.success(pa);
    }

    @PostMapping
    public R<Category> add(@RequestBody Category category,
                           HttpServletRequest req) {
        //获取登陆人的id
        long id = (long) req.getSession().getAttribute("one");
        //category.setCreateTime(LocalDateTime.now());
        //category.setUpdateTime(LocalDateTime.now());
        //category.setCreateUser(id);
        //category.setUpdateUser(id);

        categoryService.save(category);
        return R.success(category);

    }

    @DeleteMapping
    public R deleteById(Long id) {
        //调用service中自定义的方法
        categoryService.deleteById(id);

        return R.success("删除成功");
    }

    @PutMapping
    public R update(@RequestBody Category category) {
        categoryService.updateById(category);

        return R.success("删除成功");

    }

    @GetMapping("/list")
    public R<List<Category>> list(Integer type) {
        //select * from
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(type!=null,Category::getType,type);



        List<Category> list = categoryService.list(lambdaQueryWrapper);

        return R.success(list);
    }

}
